<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <div id="box">
        <p> {{ name }}</p>
        <p> {{ age }} </p>
    </div>


    <button>修改name值为yy</button>


    <script>

        function myVue(options) {
            this.el = options.el;

            const data = options.data;


            // 检测参数
            if (Object.prototype.toString.call(data) !== '[object Object]') {
                throw new Error('data必须是对象');   // 抛出错误程序就会断掉  return 
            }

            const oBox = document.querySelector(this.el);
            if (oBox === null) {
                throw new Error('el元素获取不到');
            }


            let html = oBox.innerHTML;


            // 数据劫持
            const res = {};

            for (let key in data) {
                Object.defineProperty(res, key, {
                    get() {
                        return data[key]
                    },
                    set(v) {
                        data[key] = v;
                        render(oBox, res, html);
                    }
                })
            }


            render(oBox, res, html)


            return res;

        }



        function render(oBox, res, html) {

            const reg = /{{\s*(\w+)\s*}}/g;
            const arr = html.match(reg);
            arr.forEach(item => {
                const key = reg.exec(html)[1];
                html = html.replace(/{{\s*(\w+)\s*}}/, res[key])
            })
            oBox.innerHTML = html;
        }







        const vm = new myVue({
            el: '#box',
            data: {
                name: 'cc',
                age: 20
            }
        })


        const oBtn = document.querySelector('button');
        oBtn.onclick = function () {
            vm.name = 'yy';
        }

    </script>

</body>

</html>